package grib2handler;

import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.quartz.DateBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import grib2handler.bufr.BufrDownTask;
import grib2handler.grib.GribPoolDownTask;
import grib2handler.util.PropertiesUtil;
import grib2handler.util.TimeUtil;

public class ProcessorMain {
	private final static Logger log = Logger.getLogger(ProcessorMain.class);
	private static Scheduler sched = null;
	private static boolean isStart = false;
	public static boolean init() {
		log.info("初始化");
		//调用定时下载任务  设定时间启动，每n小时运行一次。 启动时机还需要继续设置一下
		PropertyConfigurator.configure("conf/log4j.properties");
		//初始化线程池
		GribPoolDownTask.setPool(new ThreadPoolExecutor(4, 20, 10, TimeUnit.SECONDS,
    		new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.AbortPolicy()));
		BufrDownTask.setPool(new ThreadPoolExecutor(4, 20, 10, TimeUnit.SECONDS,
	    		new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.AbortPolicy()));
		try {
			SchedulerFactory sf = new StdSchedulerFactory();
			sched = sf.getScheduler();
			// get a "nice round" time a few seconds in the future...
			Date startTime = DateBuilder.dateOf(TimeUtil.getStartHour(), 0, 0, 1, 1, 2000);
			JobDetail job = JobBuilder.newJob(GribPoolDownTask.class)
					.withIdentity("job1", "group1").build();

			SimpleTrigger trigger = TriggerBuilder
					.newTrigger()
					.withIdentity("trigger1", "group1")
					.startAt(startTime)
					.withSchedule(
							SimpleScheduleBuilder
									.simpleSchedule()
									.withIntervalInHours(6)
									.repeatForever()).build();
			
			JobDetail job2 = JobBuilder.newJob(BufrDownTask.class)
					.withIdentity("job2", "group2").build();

			SimpleTrigger trigger2 = TriggerBuilder
					.newTrigger()
					.withIdentity("trigger2", "group2")
					.startAt(DateBuilder.dateOf(TimeUtil.getStartHour(), 35, 0, 1, 1, 2000))
					.withSchedule(
							SimpleScheduleBuilder
									.simpleSchedule()
									.withIntervalInHours(6)
									.repeatForever()).build();
			if(PropertiesUtil.getConfig().getBoolean("downGrib")) {
				Date ft = sched.scheduleJob(job, trigger);
				//初始化下载最近一次数据
				GribPoolDownTask.loadLastDataThread();
			}
			if(PropertiesUtil.getConfig().getBoolean("downBufr")) {
				Date ft2 = sched.scheduleJob(job2, trigger2);
				//初始化加载最近10次数据
				BufrDownTask.loadData(10);
			}
			
			log.debug(job.getKey() + "  and repeat: "
					+ trigger.getRepeatCount() + " times, every "
					+ trigger.getRepeatInterval() / 1000 + " hour");
			sched.start();
			isStart = true;
		} catch (Exception e) {
			log.error("定时任务创建失败" + e.getMessage());
			isStart = false;
			return false;
		}
		log.info("初始化完成");
		return true;
	}
	/**
	 * 销毁
	 * @return
	 */
	public static void destroy() {
		if(!isStart) {
			log.warn("没有启动成功，无法销毁");
			return;
		}
		log.info("销毁");
		try {
			if(sched != null) {
                sched.clear();
				sched.shutdown();
			}
		} catch (Exception e) {
			log.error("定时任务销毁失败" + e.getMessage());
		}
		//销毁线程池
		try {
			ThreadPoolExecutor pool = GribPoolDownTask.getPool();
			if(pool != null) {
				GribPoolDownTask.setPool(null);
				pool.shutdownNow();
			}
		} catch (Exception e) {
			log.error("GribPoolDownTask销毁线程池失败" + e.getMessage());
		}
		try {
			ThreadPoolExecutor pool = BufrDownTask.getPool();
			if(pool != null) {
				BufrDownTask.setPool(null);
				pool.shutdownNow();
			}
		} catch (Exception e) {
			log.error("BufrDownTask销毁线程池失败" + e.getMessage());
		}
		log.info("销毁完成");
		isStart = false;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		//初始化抓取服务
		init();
	}

}
